package com.keya.config;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.keya.base.output.PageData;
import com.keya.base.output.ResultData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;


@RestControllerAdvice("com.keya")
@Slf4j
public class KeyaResponseBodyAdvice implements ResponseBodyAdvice {


    @Override
    public Object beforeBodyWrite(Object returnValue, MethodParameter methodParameter,
                                  MediaType mediaType, Class clas, ServerHttpRequest serverHttpRequest,
                                  ServerHttpResponse serverHttpResponse) {

        if (returnValue == null) {
            return ResultData.success(null);
        }

        if (returnValue instanceof IPage) {
            IPage page = (IPage) returnValue;
            PageData build = PageData.build(page.getTotal(), page.getRecords());
            return ResultData.success(build);
        } else if (returnValue instanceof List) {
            List list = (List) returnValue;
            PageData build = PageData.build((long) list.size(), list);
            return ResultData.success(build);
        } else if (returnValue instanceof ResultData) {
            return returnValue;
        } else if (returnValue instanceof String) {
            return JSONObject.toJSONString(ResultData.success(returnValue));
        } else {
            return ResultData.success(returnValue);
        }

    }

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        //排除的controller路径
        String s = returnType.getExecutable().toString();
        Method method = (Method) returnType.getExecutable();
        Class<?> methodReturnType = method.getReturnType();
        return !methodReturnType.equals(ResponseEntity.class);
    }
}
